<template>
  <nav class="frame-nav"
       :class="{'frame-nav-expand': !collapse}"
       :style="isColorScheme && `--frame-nav-bg-color-level-1: ${isColorScheme.colorMain}; --frame-nav-bg-color-level-2: ${isColorScheme.colorExpand}; --frame-nav-bg-color-level-3: #003D7E;--frame-nav-hover-bg-color: rgba(255, 255, 255, .08);`"
       @transitionend="navTransitionEnd">
    <div class="frame-logo">
      <a 
        href="javascript:;"
        @click="openHome"
      >
        <img :src="logoImg">
      </a>
    </div>
    <div class="frame-search">
      <template v-if="collapse">
        <i class="el-icon-search" @click="handleSearchIconClick"></i>
      </template>
      <el-input
        v-else
        v-model="navSearchValue"
        ref="navSearchInput"
        class="frame-search-input"
        :placeholder="$t('common.base.search')"
        prefix-icon="el-icon-search"
        @input="handleNavMenuSearch"
        clearable
      >
      </el-input>
    </div>
    <div id="task-center-view"></div>
    <div id="task-center-view-copy"></div>
    <div id="product-product-nav"></div>
    <div id="task-setting-nav"></div>
    <div id="im-setting-nav"></div>
    <div class="frame-menu-scroll hide-scroll" :class="{'frame-menu-scroll-down': showSlideDown}">
       
      <ul class="frame-menu" @mouseover="handleMouseOver">
        <bar-menu 
          :menus="menus" 
          :collapse="collapse" 
          :is-color-scheme="isColorScheme" 
          :unique-opened="uniqueOpened" 
          :default-openeds="defaultMenuOpeneds" 
          :default-active="defaultActive"
          :highlight-text="navSearchValue"
        />

        <!-- <template v-for="(menu, index) in menus">
          <li :class="{
                'frame-menu-item': true, 
                'frame-menu-active': menu == currMenu,
                'frame-menu-expand': menu == currMenu
              }"
              :key="menu.menuKey"
              :id="menu.menuKey"
              @mouseenter="handlerOnMenuItemMouseEnter($event, menu)"
          >
            <a :href="menu.url ? menu.url : 'javascript:;'"
               @click.prevent="open(menu)"
               :id="`${menu.menuKey}-a`"
               :class="{'': menu.active}">
              <span class="frame-menu-icon"><i :class="['iconfont', menu.icon]"></i></span>
              <template v-if="!collapse">
                <span class="frame-menu-name">{{menu.name}}</span>
                <i class="iconfont icon-caidanjiantou-zhankai"
                   v-if="menu.menuList && menu.menuList.length > 0"></i>
              </template>
            </a>

            <ul :class="{'frame-subMenu': true,'frame-float-menu': collapse}"
                :style="{'backgroundColor':isColorScheme && !collapse? isColorScheme.colorExpand : ''}"
                v-show="!collapse && menu == currMenu">
              <li class="frame-float-menu-title">
                <h3>{{menu.name}}</h3>
              </li>
              <div class="frame-subMenu-item-wrap" :class="{'frame-collapse-wrap': !collapse}">
                <template v-for="menu in menu.menuList">
                  <li :class="{'frame-subMenu-item': true, 'frame-subMenu-active': menu.active}"
                      :style="{'background':isColorScheme && menu.active ? `${isColorScheme.colorSelected} !important`: '',
                               color:isColorScheme && menu.active ? `${isColorScheme.colorMain} !important`: ''}"
                      :key="menu.menuKey">
                    <a :href="menu.url ? menu.url : 'javascript:;'"
                       @click.prevent="open(menu)">{{menu.name}}</a>
                  </li>
                </template>
              </div>
            </ul>
          </li>
        </template> -->
      </ul>
      <li v-if="showSlideDown" class="frame-menu-item-slide-down" 
          :class="animationClassNames" @click="slideDown">
        <i class="iconfont icon-gongsimingchengxiala"></i>
      </li>
      
      <el-popover
        v-if="!navSearchValue"
        trigger="manual"
        placement="right"
        width="4"
        popper-class="menuPopper"
        v-model="showMenuPopper">
        <div v-if="!morePageMenus.length" class="menu-empty">
          <p>{{$t('frame.nav.des1')}}</p>
          <template v-if="showAppSeting">
            <span>{{$t('frame.nav.des2')}}</span>
            <div class="app-setting" @click="goAppSetting">
              <span>{{$t('common.base.toSet2')}}<i class="iconfont icon-right1"></i></span>
            </div>
          </template>
        </div>
        <div v-else ref="moreMenu" class="menu-content" @mouseleave="closeMenu()">
          <div class="menu-box" :class="menuBoxClassNames">
            <div class="menu-list">
              <bar-menu :menus="morePageMenus" :is-more="true" v-ClickOutSide="hideMoreMenus"></bar-menu>
              <!-- <div class="menu-item" v-for="(item,index) in morePageMenus" :key="index" @mouseenter="chooseMenuItem(index)" :class="index === chooseMenuIndex ? 'active' : ''">
                <div class="menu-logo" :style="{background: item.logoColor}">
                  <i class="iconfont" :class="item.icon ? item.icon : 'icon-creditcard-fill'"></i>
                </div>
                <p>{{item.name}}</p>
              </div> -->
            </div>
          </div>
          <!-- <div class="menu-line"></div>
          <div class="second-menu">
            <div class="menu-item" v-show="secondMenus.length <= 0">
              <p>暂无更多...</p>
            </div>
            <div class="menu-item" v-for="(item,index) in secondMenus" :key="index" @click.prevent="open(item,'more')">
              <p>{{item.name}}</p>
            </div>
          </div> -->
        </div>
        <template slot="reference" ref="moreMenuBtn">
          <li @click="showMenuPopper = true" class="frame-menu-item" :class="isColorScheme && isColorScheme.colorMain ? 'frame-menu-more-scheme' : 'frame-menu-more'" :style="{'backgroundColor': isColorScheme && isColorScheme.colorMain ? isColorScheme.colorMain : ''}">
            <a>
              <span class="frame-menu-icon more">
                <div class="more-back"></div>
                <i class="iconfont icon-gengduo"></i>
              </span>
              <template v-if="!collapse">
                <span class="frame-menu-name">{{$t('common.base.moreApplications')}}</span>
              </template>
            </a>
          </li>
        </template>
      </el-popover>
    </div>
  </nav>
</template>

<script>
import ClickOutSide from '@src/util/clickoutside';
import * as guideApi from '@src/api/GuideApi'
import { getRootWindowInitData, setRootWindowInitData } from '@src/util/window'
import _ from 'lodash';
import MenuIcon from '../model/MenuIcon';
import BarMenu from './BarMenu.vue';

import { getLocalesOssUrl } from '@src/util/assets'

const Logo = getLocalesOssUrl('/logo.png');
const LogoEN = getLocalesOssUrl('/common/logo-en.png');

import MiniLogo from '@src/assets/svg/logo.svg';
import { storageGet, storageSet } from '@src/util/storage';
import { isShowCardWorkTime } from '@shb-lib/version';
import GuideContent from '@src/component/guide/contentCom/ProductFrameNav.vue';
// 新存储工具方法
import * as StorageUtil from '@src/util/storage.ts';
/* enum */
import StorageModuleEnum from '@model/enum/StorageModuleEnum';
/* util */
import { cloneDeep, isArray } from '@src/util/type';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import PageInfo from 'pub-bbx-global/pageType/dist'

import {
  PRODUCT_FRAME_NAV
} from '@src/component/guide/productV2Store';

import {
  TASK_SETTING_FRAME_NAV,
  IM_SETTING_FRAME_NAV
} from '@src/component/guide/taskSettingStore';
/* mixins */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'

import { t } from '@src/locales'

import PinyinMatch from 'pinyin-match'

const MenuMarginHeight = 42;
const MenuItemHeight = 48;

export default {
  name: 'frame-nav',
  mixins: [VersionControlTaskMixin],
  props: {
    collapse: {
      type: Boolean,
      default: false
    },
    source: {
      type: Array,
      default: () => []
    },
    moreMenus: {
      type: Array,
      default: () => []
    },
    newLogo: {
      type: String,
      default: '',
    },
    defaultActive: {
      type: String,
      default: '',
    },
  },
  inject: ['initData'],
  components: {
    BarMenu
  },
  data () {
    return {
      showAnimation: true,
      showSlideDown: false,
      menus: this.source,
      morePageMenus: this.moreMenus,
      menuIcon: MenuIcon,
      currMenu: null,
      bodyHeight: 0,
      worktimeNoEnter: true,
      openSecondStep:0,
      showMenuPopper: false,
      showSecondMenuPopper: false,
      secondMenus:[],
      chooseMenuIndex:-1,
      currentTab: {},
      defaultMenuOpeneds: [],
      uniqueOpened: false,
      navSearchValue: '',
    };
  },
  watch: {
    source() {
      this.handleNavMenuSearch();
    },
    moreMenus() {
      this.morePageMenus = this.moreMenus
    },
    collapse(){
      this.initSlideState()
    },
    showAnimation: {
      immediate: true,
      handler(newValue) {
        if (newValue) {
          setTimeout(() => {
            this.showAnimation = false
          }, 2000)
          setTimeout(() => {
            this.showAnimation = true
          }, 12000)
        }
      }
    },
  },
  computed: {
    animationClassNames() {
      return {
        'slide-down-animation': this.showAnimation,
        'frame-menu-item-slide-down__search': this.navSearchValue
      }
    },
    // 是否有系统管理应用配置的权限
    showAppSeting() {
      return this.initData.showAppSeting
    },
    isShowUserGuide() {
      return getRootWindowInitData().isShowUserGuide
    },
    isShowCardWorkTime () {
      return this._isShowCardWorkTime
    },
    logoImg () {
      
      // 自定义菜单返回的Logo判断  
      if(this.collapse && this.initData.logoVo && this.initData.logoVo.foldLogoUrl){
        return this.initData.logoVo.foldLogoUrl
      } 
      
      if(!this.collapse && this.initData.logoVo && this.initData.logoVo.expandLogoUrl){
        return this.initData.logoVo.expandLogoUrl
      }
      
      let logoImage;
      
      if(this.initData.logo && this.collapse){
        logoImage = this.initData.logo.smallLogo
      }else if(this.initData.logo && !this.collapse){
        logoImage = this.initData.logo.bigLogo
      }
      else if(!this.initData.logo && !this.collapse){
        logoImage = this.unfoldDefaultLogo
      }
      else if(!this.initData.logo && this.collapse){
        logoImage = MiniLogo
      }
      
      return logoImage;
    },
    locale() {
      return this.$i18n.locale
    },
    isZH() {
      return this.locale === 'zh'
    },
    unfoldDefaultLogo() {
      return this.isZH ? Logo : LogoEN
    },
    isCustomLogo(){
      return this.initData.logo
    },
    isColorScheme(){
      // 库柏自定义菜单背景色
      // return {
      //   "colorSelected":"#fff",
      //   "colorButton":"#0075F0",
      //   "colorMain":"#005BBB",
      //   "colorExpand":"#004791"
      // }
      return this.initData.colorScheme
    },
    clientHeight() {
      return document.body.clientHeight;
    },
    isMenuHeightLimit() {
      return this.clientHeight < (
        (this.morePageMenus.length * MenuItemHeight) + MenuMarginHeight
      )
    },
    menuBoxClassNames() {
      return {
        'menu-box-scroll': this.isMenuHeightLimit
      }
    },
    allMenuList(){
      const moreMenuList = this.morePageMenus.map(item=> {
        item.icon = null 
        return item
      })

      return this.source.concat([{ logo: 'iconfont icon-gengduo', name: t('common.base.moreApplications'), menuKey: 'MORE_APP_KEY', menuList: moreMenuList}])
    }
  },
  methods: {
    /**
     * Description 关闭是否折叠
     * @returns {any}
     */
    handleSearchIconClick() {
      this.$emit('update:collapse', false);
      this.$nextTick(()=> this.$refs.navSearchInput.focus())
    },
    /**
     * Description 搜索菜单的input事件
     * @param {any} function(
     * @returns {any}
     */
    handleNavMenuSearch: _.debounce(function(){
      const [ menus = [], menuKeyArray ] = this.filterMenusForSearchValue(this.allMenuList, this.source)
      this.menus = menus
      this.uniqueOpened = !this.navSearchValue
      this.defaultMenuOpeneds = menuKeyArray

      this.$nextTick(()=> {
        this.initSlideState()
        // this.handleSetNavTextHighlightForSearchValue()
      })
    }, 500),
    /**
     * Description  相关菜单树搜索（返回层级是如果命中一级就返回当前一级以及它的子集）
     * @param {any} menu 
     * @param {any} originMenu
     * @param {any} navSearchValue=this.navSearchValue
     * @param {any} menuKeyArray=[]
     * @returns {any}
     */
    filterMenusForSearchValue(menu, originMenu, navSearchValue = this.navSearchValue, menuKeyArray = []) {
      // 如果没有搜索结果直接返回原的菜单栏
      if(!navSearchValue) return [originMenu, []]

      const menuArray = []
      for(let i = 0 ;i < menu.length; i++) {
        const menuItem = _.cloneDeep(menu[i])
        // 相关菜单名称命中
        if(PinyinMatch.match(this.getMenuName(menuItem), navSearchValue)) {
          menuArray.push(menuItem)
        } 
        // 判断是否有子集
        if(Array.isArray(menuItem.menuList) && menuItem.menuList.length) {
          // 判断当前有子集的是否已经在返回结果中如果存在直接轴下一个循环
          const existMenuArrayIndex = menuArray.findIndex(item=> item.menuKey === menuItem.menuKey)
          const childMenuList = menuItem.menuList
          // // 递归查找子集
          const filteredChildMenuList = this.filterMenusForSearchValue(childMenuList, originMenu, navSearchValue, menuKeyArray)[0]
          // 判断子集是否有数据处理
          if(filteredChildMenuList.length > 0) {
            // 推入将对应的父级key作为默认展开
            menuKeyArray.push(menuItem.menuKey)
            menuItem.menuList = filteredChildMenuList
            existMenuArrayIndex === -1 && menuArray.push(menuItem)
          }
        }
      }
      return [menuArray, menuKeyArray]
    },

    /**
     * Description 设置搜索结果字符高亮
     * @returns {any}
     */
    handleSetNavTextHighlightForSearchValue() {
      // 搜索值
      const trimLowerCaseSearchValue = this.navSearchValue.trim().toLowerCase()

      // 没有值的时候情况并且清除高亮
      if(!trimLowerCaseSearchValue) {
        CSS.highlights.clear();
        return
      }
      // 所有相关title的dom数组
      const navTitleDomList = document.querySelectorAll('.nav-title')
      // 处理相关高亮的文本
      const textRanges = Array.prototype.map.call(navTitleDomList, el=> {
        const text = el.textContent.toLowerCase()
        const indices = [];
        let startPos = 0;
        while (startPos < text.length) {
          const index = text.indexOf(trimLowerCaseSearchValue, startPos);
          if (index === -1) break;
          indices.push(index);
          startPos = index + trimLowerCaseSearchValue.length;
        }

        return indices.map((index) => {
          // https://developer.mozilla.org/zh-CN/docs/Web/API/Range  表示一个包含节点与文本节点的一部分的文档片段。
          const range = new Range();
          range.setStart(el.firstChild, index);
          range.setEnd(el.firstChild, index + trimLowerCaseSearchValue.length);
          return range;
        });
      }).filter(item=> item.length)


      // https://developer.mozilla.org/zh-CN/docs/Web/API/Highlight CSS 自定义高亮 API
      // eslint-disable-next-line no-undef
      const searchResultsHighlight = new Highlight(...textRanges.flat());

      // 注册高亮
      CSS.highlights.set('nav-text-search-result', searchResultsHighlight);
    },

    /**
     * Description 获取菜单的名称（兼容国际化问题）
     * @param {any} menuItem
     * @returns {any}
     */
    getMenuName(menuItem) {
      return menuItem.options?.nameLanguage?.[this.$i18n.locale] || menuItem.options?.name || menuItem.name
    },
    hideMoreMenus() {
      this.$nextTick(()=> {
        if(this.showMenuPopper) this.showMenuPopper = false;
      })
    },
    // 转义url中css无法识别字符
    escapeSelector(selector) {
      return selector.replace(/(&)/g, '\\\$1');
    },
    // 获取当前active的tab
    watchTab(tab) {
      this.currentTab = tab
      setTimeout(() => {
        this.$nextTick(()=>{
          const escapedId = this.escapeSelector(`#frame_tab_${this.currentTab.id}`);
          const iframe = document.querySelector(escapedId); 
          if (iframe) {
            iframe?.contentDocument?.addEventListener('click', this.hideMoreMenus)
          }
        })
      }, 500);
    },
    handleMouseOver(e){
      const ele = document.querySelector('.el-menu--collapse');
      if(!ele) return;
      if(this.showMenuPopper) this.showMenuPopper = false;
    },
    slideDown(e){
      e.stopPropagation()
      let ele = document.querySelector('.frame-menu-scroll');
      let height = ele.clientHeight;
      let menuEle = ele.querySelector('.frame-menu');
      let menuEleHeight = menuEle.clientHeight;
      // ele.scrollTop += height; //直接滑动
      // 采用动画滑动
      this.scrollToTopAnimation(ele, height);
      if(ele.scrollTop + height >= menuEleHeight) {
        this.showSlideDown = false;
      }
    },
    initSlideState(){
      let ele = document.querySelector('.frame-menu-scroll');
      let height = ele.clientHeight;
      let menuEle = ele.querySelector('.frame-menu');
      let menuEleHeight = menuEle.clientHeight;
      // 留个缓冲空间
      if(ele.scrollTop + height >= menuEleHeight - 10) {
        this.showSlideDown = false; 
      } else {
        this.showSlideDown = true; 
      }
    },
    scrollToTopAnimation(ele, totalScrollDistance) {
      let step = totalScrollDistance / 5
      let time = 5;
      let _timer = setInterval(() => {
        if(time > 0) {
          time--;
          ele.scrollTop += step;
        } else {
          clearInterval(_timer);
        }
      }, 20)
    },
    goAppSetting(){
      this.showMenuPopper = false;
      openAccurateTab({
        type: PageRoutesTypeEnum.PageFoundationMenuSetting
      })
    },
    closeMenu(){
      this.chooseMenuIndex = -1;
      this.secondMenus = [];
    },
    chooseMenuItem(index){
      this.chooseMenuIndex = index;
      this.secondMenus = this.morePageMenus[index].menuList;
    },
    goSetting(){
      this.showMenuPopper = false;
      openAccurateTab({
        type: PageRoutesTypeEnum.PageFoundationSetting
      })
    },
    navTransitionEnd (event) {
      // 只监听nav宽段变化
      if (event.target != this.$el || event.propertyName != 'width') return;
      this.$emit('collapse-changed')
      
    },
    /** 将后端返回的菜单，重整为多根树形结构 */
    buildMenus (source, parent) {
      let menus = [];
      let otherMenus = [];

      for (let i = 0; i < source.length; i++) {
        let menu = source[i]
        if (menu.parent == parent) {
          menus.push(menu);
        } else {
          otherMenus.push(menu)
        }
      }

      if (menus.length > 0) {
        for (let j = 0; j < menus.length; j++) {
          let subMenu = menus[j];
          let subRes = this.buildMenus(otherMenus, subMenu.menuKey);

          subMenu.children = subRes.menus;
          otherMenus = subRes.otherMenus;
        }
      }

      return { menus, otherMenus };
    },
    open (menu, type) {
      // console.log(menu)
      // 如果有子菜单，展开子菜单
      if (menu.menuList && menu.menuList.length > 0) {
        this.currMenu = this.currMenu?.menuKey == menu.menuKey ? '0' : menu;
        this.$emit('update:collapse', false);
        this.getGuideStyle(this.currMenu)
        return
      }
      
      if (!menu.url) return;

      let parentMenu = '0';

      this.menus.forEach(item => {
        item.active && (item.active = false)
        if(item.menuList){
          item.menuList.forEach(i=>{
            i.active && (i.active = false)
            if(i.menuKey == menu.menuKey) parentMenu = item
          })
        }
      })

      if(!menu.menuList && type === 'more'){
        this.showMenuPopper = false;
        this.chooseMenuIndex = -1;
        // this.$refs[`popover-menu_${item.menuKey}`][0].doClose();
      }

      this.currMenu = parentMenu;
      this.$set(menu, 'active', true);
      
      this.$emit('open', menu)
    },
    openForNav(){
      this.showMenuPopper = false;
    },
    // 让新手引导动态变化高度
    getGuideStyle(currMenu){
      if(currMenu && currMenu.name === '工单中心'){
        document.getElementById('task-center-view-copy').style.top = '220px'
      }else{
        this.$nextTick(()=>{
          let a = document.getElementById('M_TASK').getBoundingClientRect().top
          let b = `${a + 35}px`
          document.getElementById('task-center-view-copy').style.top = b
        })
      }
    },
    openHome () {
      this.$emit('open-home')
    },
    /**
     * 为menus的每个条目设置y轴占用高度数据 供计算
     */
    setMenuOffsetData () {
      const baseTitleHeight = 51; // 菜单栏标题的高度
      const baseItemHeight = 40; // 菜单栏每个条目的高度

      // 获取menus的位置，记录menuItem 的offsetTop
      this.menus = this.menus.map(menu => {
        let key = (menu || {}).menuKey;
        if (!key) return menu;

        let dom = document.querySelector(`#${key}`);
        if (!dom) return menu;
        // 获取距离顶部的高度
        let offsetTop = dom.offsetTop || 0;
        // menu._offsetTop = offsetTop || 0;
        // 记录每个条目 距离顶部高度+自身占用高度， 用于比较body.offsetHeight
        let childrenLength = (menu.menuList && menu.menuList.length) || 0;
        menu.__bottomToTop = offsetTop + baseTitleHeight;
        menu.__totalHeight = offsetTop + baseTitleHeight + (baseItemHeight * childrenLength);

        return menu;
      })
    },
    /**
     * 注册窗口大小变更监听器
     */
    registerResizeListener () {
      try {
        let _scope = this;
        let dom = document.body;
        this.bodyHeight = dom.offsetHeight;

        window.addEventListener('resize', _.debounce(function () {
          _scope.bodyHeight = dom.offsetHeight || 0;
        }, 167));
      } catch (e) {
        console.error(e);
      }
    },
    /**
     * 获取菜单条目外围容器的样式，来确保显示不会被裁减
     */
    getMenuItemWrapStyle (menu) {
      let totalHeight = menu.__totalHeight || 0;
      let bottomToTop = menu.__bottomToTop || 0;
      // 如果该菜单的子条目显示不会被当前屏幕裁剪
      if (totalHeight <= this.bodyHeight) return '';

      let remindHeight = this.bodyHeight - bottomToTop;
      const minHeight = 40; // 菜单条目的高度
      // 看不到一个半完整的条目停止计算
      if (remindHeight < (minHeight / 2)) return '';

      return `max-height: ${remindHeight}px; overflow-y: auto;`;
    },
    init () {
      this.setMenuOffsetData();
      this.registerResizeListener();
      let hasEntered = storageGet('worktime_guid');
      if (hasEntered) {
        this.worktimeNoEnter = false;
      }
    },
    // 打开工单中心
    openMenu () {
      let menu = this.menus.find(item => {
        return item.menuKey === PageInfo.pageTaskList.id
      })
      this.open(menu)
    },
    taskCenter () {
      this.$Guide([{
        content:this.$t('frame.nav.taskGuide.tips1'),
        fixedStep: true,
        nowStep: 2,
        totalStep:5,
        gStyle:'left:20px',
        arrowOutsideStyle:{
          left:'20px'
        },
        id: 'task-center-view-copy',
        domId: 'task-center-view',
        domObj:()=>{
          return document.getElementById('task-center-view-copy')
        },
        // needCover: false,
        finishBtn: this.$t('common.base.nextStep'),
      }], 0, '', (e) => {
        return new Promise((resolve, reject) => {
          if(e.type == 'finish') {
            openAccurateTab({
              type: PageRoutesTypeEnum.PageCreateTask,
            })
          }else if(e.type == 'stop'){
            this.closeGuide()
          }
          resolve()
        })
      }).create()
    },
    closeGuide(){
      guideApi.closeGuide({ua: 'web'}).then(res=>{
        if(res.status == 0) {
          sessionStorage.removeItem('isUserGuide')
          let rootWindowInitDataData = getRootWindowInitData()
          rootWindowInitDataData.isShowUserGuide = true
          setRootWindowInitData(rootWindowInitDataData)
        }
      })
    },
    handlerOnMenuItemMouseEnter(event, menu) {
      const target = event.target;
      const boundingClientRect = target.getBoundingClientRect();
      const frameSubMenuElement = target.querySelector('.frame-float-menu');
      const menuChildList = isArray(menu?.menuList) ? menu.menuList : [];
      
      if (!frameSubMenuElement) return;
      
      // 底部安全距离
      const safeAreaHeight = 20;
      // 屏幕显示高度
      const clientHeight = document.body.clientHeight;
      // 子菜单头部的高度
      const subMenuHeaderHeight = 50;
      // 子菜单的高度 (子菜单头部的高度 + 所有子菜单的高度)
      const subMenuHeight = subMenuHeaderHeight + (menuChildList.length * 40);
      // 当前元素位于屏幕顶部的高度距离
      const currentElementTop = boundingClientRect.top;
      // 完整显示菜单所需要的所有高度
      const fullDisplayMenusHeight = currentElementTop + subMenuHeight;
      
      let top = null
      
      if (fullDisplayMenusHeight > clientHeight) {
        top = clientHeight - subMenuHeight - safeAreaHeight;
      } else {
        top = boundingClientRect.top;
      }
      
      frameSubMenuElement.style.top = `${top}px`;
    }
  },
  created() {
    window.toOpenMenu = () =>{
      let isShowGuide = sessionStorage.getItem('isUserGuide') ? sessionStorage.getItem('isUserGuide') : 0
      if( isShowGuide ){
        this.taskCenter()
        this.openMenu()
      }
      
    }
    this.$nextTick(() => {
      let height = (document.documentElement.clientHeight - 90 ) / 3 * 2;
      let obj = document.querySelector('.menu-box');
      let menu = document.querySelector('.menu-content');
      if(obj && obj[0]) {
        obj[0].style.maxHeight = `${height}px`;
      }
      if(menu && menu[0]) {
        menu[0].style.height = `${height}px`;
      } 
    })
    this.$eventBus.$on('openForNav', this.openForNav);
    this.$eventBus.$on('watchTab', this.watchTab);
  },
  mounted () {
    this.init()
    this.$nextTick(async() => {
      this.initSlideState();
      document.querySelector('.frame-menu-scroll').addEventListener('scroll', ()=>{
        this.initSlideState();
      })
      if(!this.isShowUserGuide) return 
    })
  },
  beforeDestroy() {
    this.$eventBus.$off('guide', this.open);
    this.$eventBus.$off('openForNav', this.openForNav);
    this.$eventBus.$off('watchTab', this.watchTab);
    document.querySelector(`#frame_tab_${this.currentTab.id}`)?.contentDocument?.removeEventListener('click', this.hideMoreMenus)
  },
  directives: {
    ClickOutSide
  }
}
</script>

<style lang="scss">
$frame-nav-width: 184px;

.frame-nav {
  flex: 0 0 50px;
  width: 50px;
  height: 100%;
  background-color: $frame-nav-bg-color-level-1;
  // box-shadow: 1px 0 8px rgba(0, 0, 0, 0.125);
  transition: width ease 0.2s;
  position: relative;
  z-index: 9;
  a {
    text-decoration: none !important;
  }
  .frame-menu-scroll {
    overflow: auto;
    height: calc(100% - 152px);
  }
  .frame-menu-scroll-down {
    overflow: auto;
    height: calc(100% - 186px);
  }
}

#task-center-view{
}
#task-center-view-copy{
  position: absolute;
  left: 259px;
}
.frame-nav .frame-menu-scroll-hide {
  // width: 250px;
  overflow-y: hidden;
  // height: calc(100% - 44px);
  height: calc(100% - 186px);
  // margin-right: -40px;
}
.frame-nav.frame-nav-expand {
  width: $frame-nav-width;
  flex: 0 0 $frame-nav-width;
  overflow: hidden;

  .frame-menu-scroll {
    overflow: auto;
    // height: calc(100% - 44px);
    height: calc(100% - 152px);
    // margin-right: -40px;
  }
  .frame-menu-scroll-down {
    overflow: auto;
    // height: calc(100% - 44px);
    height: calc(100% - 186px);
    // margin-right: -40px;
  }

  .frame-menu {
    width: $frame-nav-width;
  }

  .frame-menu-item {
    width: $frame-nav-width;
    overflow: hidden;
  }

  .frame-subMenu-item {
    color: #fff;

    & > a {
      padding: 13px 15px 13px 46px;
    }

  }

  .frame-float-menu-title {
    display: none;
  }
}

.frame-menu {
  .el-menu{
    border: none;
  }
}

.frame-logo {
  height: 50px;
  // border-bottom: 1px solid rgba(0, 0, 0, 0.1);

  a {
    height: 100%;
    width: 100%;

    display: flex;
    flex-flow: row nowrap;
    align-items: center;
    justify-content: center;
    overflow: hidden;
  }

  img {
    display: block;
    margin: 0;
    height: 100%;
    max-width: 100%;
    padding: 6px;
  }
}

.frame-menu {
  margin: 0;
  padding: 0;
  list-style: none;
}

.frame-menu-item {
  position: relative;
  margin: 0;
  padding: 0;
  min-height: 50px;
  transition: background-color ease 0.3s;

  &:hover {
    .frame-float-menu {
      display: block !important;
    }
  }

  & > a {
    position: relative;
    display: flex;
    flex-flow: row nowrap;
    align-items: center;
    color: #fff;
    font-size: 14px;

    i.iconfont {
      font-size: 16px;
    }

    i.icon-caidanjiantou-zhankai {
      margin-right: 16px;
    }

    i.red-dot {
      margin-right: 20px;
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: red;
    }
  }
   &.frame-menu-more {
    // background-color: $color-nav-hover;
    position: absolute;
    bottom: 0;
    list-style: none;
    // padding: 5px 0;
    background-color: $frame-nav-bg-color-level-1;

    > a{
      cursor: pointer;
    }
    &:hover .more-back{
      background: $color-primary;
    }
  }
  //库柏自定义色
  &.frame-menu-more-scheme {
    position: absolute;
    bottom: 0;
    list-style: none;
    > a{
      cursor: pointer;
      &:hover{
        // background-color: $color-nav-hover;
      }
    }
  }
}

.frame-menu-active > a:before {
  content: "";
  position: absolute;
  width: 3px;
  height: 30px;
  top: 10px;
  left: 0;
  background-color: #fff;
}

.frame-menu-expand .icon-caidanjiantou-zhankai {
  transform: rotateZ(180deg);
}

.frame-menu-icon {
  width: 50px;
  height: 50px;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: center;
  .icon-more {
    width: 20px;
    height: 20px;
    background: $color-primary-light-6;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  &.more{
    .iconfont{
      font-family: "iconfont" !important;
      font-style: normal;
		  -webkit-font-smoothing: antialiased;
		  -moz-osx-font-smoothing: grayscale;
    &.icon-gengduo{
      font-size: 18px !important;
      z-index: 1;
    }
  }
  .more-back{
      width: 15px;
      height: 15px;
      border-radius: 50%;
      position: absolute;
  }
  // &:hover .icon-gengduo::before{
  //     width: 18px;
  //     height: 18px;
  //     border-radius: 50%;
  //     // background: $color-primary-light-6;
  //     background: #1db7b5;
  //   }

  }  
}

.frame-menu-name {
  flex: 1;
}

.frame-subMenu {
  background-color: $color-nav-secondary;
  margin: 0;
  padding: 0;
}

.frame-subMenu-item-wrap {
  position: relative;
}

.frame-collapse-wrap {
  padding: 12px 0;
}

.frame-subMenu-item {
  display: block;
  position: relative;
  width: 100%;
  transition: background-color ease 0.3s, color ease 0.3s;


  &.frame-subMenu-active {
    @include backgroundColorImportant();
    color: #fff !important;
  }

  & > a {
    width: 100%;
    display: block;
    padding: 10px 25px;
    line-height: 20px;
    color: inherit;
  }
}

.frame-float-menu {
  display: none;
  position: absolute;
  left: 50px;
  top: 0;
  overflow: hidden;
  width: 176px;
  background-color: #fff;
  box-shadow: 1px 1px 4px 0 rgba(0, 0, 0, 0.1);
}

.frame-float-menu-title h3 {
  margin: 0;
  font-size: 16px;
  padding: 13px 25px;
  line-height: 24px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  cursor: default;

  a {
    color: $text-color-primary;
    width: 100%;
    display: block;
  }
}

.frame-float-menu {
  position: fixed !important;
}

.frame-menu-item-slide-down {
  display: flex;
  height: 40px;
  width: 100%;  
  background: $frame-nav-bg-color-level-1;
  align-items: center;
  justify-content: center;
  position: absolute;
  align-items: center;
  bottom: 50px;
  i {
    color: #fff;
    font-size: 14px;
  } 
  &__search{
    bottom: 0;
  }
}

.slide-down-animation{
  // animation: arrow-down 1s ease-in-out 2s 2 alternate;
  animation: arrow-down 1s linear infinite;
}

@keyframes arrow-down{
  from { transform: translate(0,0) }
  to { transform: translate(0,4px) }
}

.menu-box-scroll {
  overflow-y: scroll !important;
  max-height: calc(100vh - 50px) !important;
}

.frame-search{
  padding: 10px 16px;
  &-input{
    input{
      background: rgba(255, 255, 255, 0.1);
      border: none;
      color: #fff !important;
    }
  }
  .el-icon-search{
    color: #fff;
    font-size: 16px;
    cursor: pointer;
  }
}
</style>

<style lang="scss">
.frame-menu-scroll {
  .el-menu--collapse{
    width: 50px;
  }
}
.menu-list {
  .el-submenu__title .el-submenu__icon-arrow {
    color: #909399;
  }
}
.child-menu {
  .el-menu--popup-right-start {
    .child-menu {
      top: 0!important;
    }
  }  
}
.frame-menu {
  .el-submenu__title, 
  .el-menu-item {
    height: 50px;
    line-height: 50px;
    font-size: 0;
  }
  .el-submenu .el-menu-item {
    height: 46px;
    line-height: 46px;
    min-width: 184px;
  }
  .el-menu--collapse {
    .el-submenu {
      .el-submenu__title {
        .el-icon-arrow-right{
          display: none!important;
        }
      }
    }
  }
}

::highlight(nav-text-search-result) {
  color: $color-primary;
}
</style>
